<?php

//
// +---------------------------------------------------------+
// | 开发组
// +---------------------------------------------------------+
// | Copyrigh  (c)  2020 The PHP Group
// +---------------------------------------------------------+
// | 后台菜单
// +---------------------------------------------------------+
// | zxc
// | php后端开发
// |
// +———————————————————+
//

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class AdminMenu extends Model
{

    protected $table = 'admin_menu';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];


    /**
     * 获取菜单结构树
     * @return type
     */
    public static function getTree()
    {
        $nodelist = self::where(['type' => 1, 'status' => 1])->select('id', 'pid', 'name', 'url', 'icon_font')->orderBy('sort', 'asc')->get()->toArray();
        if ($nodelist) {
            return self::makeTree($nodelist);
        }
        return [];
    }

    public static function makeTree($list, $pid = 0, $idsArr = [])
    {
        $dataArr = [];
        foreach ($list as $key => $item) {
            if ($item['pid'] == $pid) {
                if ($idsArr && in_array($item['id'], $idsArr)) {
                    $item['is_select'] = 1;
                }
                $item['son'] = self::makeTree($list, $item['id'], $idsArr);
                $dataArr[] = $item;
            }
        }

        return $dataArr;
    }

    public static function getTreeByMenu($idsArr = [])
    {
        $nodelist = self::where(['type' => 1, 'status' => 1])->select('id', 'pid', 'name', 'url', 'icon_font')->orderBy('sort', 'asc')->get()->toArray();
        if ($nodelist) {
            return self::makeTree($nodelist, 0, $idsArr);
        }
        return [];
    }

    public static function getMyTree($idsArr = [])
    {
        if ($idsArr) {
            if ($idsArr == 'all') {
                $nodelist = self::where(['type' => 1, 'status' => 1])->select('id', 'pid', 'name', 'url', 'icon_font')->orderBy('sort', 'asc')->get()->toArray();
            } else {
                $nodelist = self::where(['type' => 1, 'status' => 1])->whereIn('id', $idsArr)->select('id', 'pid', 'name', 'url', 'icon_font')->orderBy('sort', 'asc')->get()->toArray();
            }
            if ($nodelist) {
                return self::makeTree($nodelist, 0);
            }
        }
        return [];
    }
}